#| echo: false
#| warning: false
#| message: false
#| fig-align: "center"
#| fig-height: 6
library(tidyverse)
library(plotly)
library(scales)
library(DT)
# --- FUNCIÓN AUXILIAR PARA TABLAS DE DESCARGA ---
# Esta función crea estandariza el botón de Excel para todos los gráficos
make_download_table <- function(data_input, filename_label = "datos") {
datatable(
data_input,
extensions = 'Buttons',
rownames = FALSE,
options = list(
dom = 'Bfrtip',
buttons = list(
list(extend = 'excel', filename = filename_label, title = filename_label),
list(extend = 'csv', filename = filename_label)
),
pageLength = 5, # Pocas filas para no ocupar mucho espacio
scrollX = TRUE,
language = list(url = '//cdn.datatables.net/plug-ins/1.10.11/i18n/Spanish.json')
)
)
}
# 1. DATOS
csv_data <- "Grupo,Anio,Atenciones
Población afroperuana,2019,35
Población afroperuana,2020,55
Población afroperuana,2021,74
Población afroperuana,2022,85
Población afroperuana,2023,39
Población afroperuana,2024,59
Población afroperuana,2025,75
Poblaciones amazónicas,2019,1752
Poblaciones amazónicas,2020,1575
Poblaciones amazónicas,2021,2342
Poblaciones amazónicas,2022,2535
Poblaciones amazónicas,2023,838
Poblaciones amazónicas,2024,4494
Poblaciones amazónicas,2025,4057
Poblaciones andinas,2019,1941
Poblaciones andinas,2020,1173
Poblaciones andinas,2021,1556
Poblaciones andinas,2022,1486
Poblaciones andinas,2023,657
Poblaciones andinas,2024,1678
Poblaciones andinas,2025,1664
Población mestiza,2019,190886
Población mestiza,2020,113536
Población mestiza,2021,160236
Población mestiza,2022,186618
Población mestiza,2023,57002
Población mestiza,2024,212553
Población mestiza,2025,198500"
data_ht <- read.csv(text = csv_data)
# 2. COLORES FLOURISH (Extraídos del código)
cols_ht <- c(
"Población afroperuana" = "#a193f3",
"Poblaciones amazónicas" = "#eb8484",
"Poblaciones andinas" = "#ffe281",
"Población mestiza" = "#d6a4e9"
)
# 3. GRÁFICO DE ÁREAS (FACETADO PARA MEJOR VISIBILIDAD)
# Dado que los rangos son MUY distintos (75 vs 200,000), separar en facetas con escala libre es lo mejor.
p <- ggplot(data_ht, aes(x = Anio, y = Atenciones, fill = Grupo)) +
geom_area(alpha = 0.8) +
geom_line(aes(color = Grupo), size = 1) +
geom_point(aes(color = Grupo,
text = paste0("<b>", Grupo, "</b><br>",
"Año: ", Anio, "<br>",
"Atenciones: ", format(Atenciones, big.mark = ","))),
size = 1.5) +
scale_fill_manual(values = cols_ht) +
scale_color_manual(values = cols_ht) +
facet_wrap(~Grupo, scales = "free_y", ncol = 2) + # Escalas libres vitales aquí
scale_y_continuous(labels = comma) +
labs(x = "Año", y = "Atenciones") +
theme_minimal() +
theme(
legend.position = "none",
strip.text = element_text(face = "bold", size = 11),
panel.grid.minor = element_blank()
)
ggplotly(p, tooltip = "text") %>%
layout(
title = list(text = "", font = list(size = 18)),
margin = list(t = 60, b = 60, l = 60)
) %>%
config(responsive = TRUE, displayModeBar = FALSE)